﻿using DapperExtensions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WeChatParking.Web.UrlAuthorize;

namespace WeChatParking.Web.Controllers
{
    public class AdminController : AdminBaseController
    {
        [UrlAuthorize]
        public ActionResult Index()
        {
            var user = base.LoginUser;
            if (user == null)
                return RedirectToAction("Login", "Admin");
            return View(user);
        }
        #region 登陆登出
        public ActionResult Login()
        {
            return View();
        }
        [HttpPost, ValidateAntiForgeryToken]
        public ActionResult Login(string enterprise, string username, string password)
        {
            var loginBll = new Core.BLL.LoginUser();
            var user = loginBll.ValidUser(enterprise, username, password);
            if (user == null)
                return base.Fail("用户名或密码错误");
            base.OnLogin(user);
            return base.OK();
        }
        /// <summary>
        /// 登出
        /// </summary>
        /// <returns></returns>
        public ActionResult Logoff()
        {
            base.OnLogoff();
            return Redirect("~/Admin/Login");
        }
        #endregion

        #region 修改密码
        [UrlAuthorize]
        public ActionResult ChangePass()
        {
            return View(base.LoginUser);
        }

        [HttpPost, UrlAuthorize]
        public ActionResult ChangePassPost(string oldpass, string newpass)
        {
            if (string.IsNullOrEmpty(newpass) || newpass.Length < 5)
                return Fail("密码长度至少5位");
            var user = base.LoginUser;
            var loginBll = new Core.BLL.LoginUser();
            string msg = loginBll.ChangePassword(user.UserCode, oldpass, newpass);
            Core.LogHelper.Info(string.Format("变更密码：{0}", user.UserCode), Entity.Enums.LogType.ChangePassword);
            return msg.Length == 0 ? base.OK() : base.Fail(msg);
        }
        #endregion

        #region 角色权限管理
        [UrlAuthorize]
        public ActionResult Role()
        {
            return View();
        }
        [HttpPost, UrlAuthorize]
        public ActionResult RoleQuery()
        {
            string role_name = Request.Form["role_name"];
            var filter = base.GetPageInfo();
            bool asc = filter.asc;
            if (string.IsNullOrWhiteSpace(filter.sort)) filter.sort = "update_time";
            Core.BLL.Role bll = new Core.BLL.Role();
            int EnterpriseID = base.GetEnterpriseID();
            if (EnterpriseID == 10001)
                return base.Fail("登陆异常请重新登陆");
            var data = bll.GetRoleQuery(EnterpriseID, role_name, filter);
            return base.ToGridJson(data);
        }
        [HttpPost, UrlAuthorize]
        public ActionResult SaveRole(Entity.RoleQuery role)
        {
            var bll = new Core.BLL.Role();
            var user = base.LoginUser;
            if (role.role_id > 0)
            {
                string errMsg = bll.Update(role.role_id, role.role_name, user.UserName);
                if (errMsg.Length > 0)
                    return Fail(errMsg);
            }
            else
            {
                int newid = bll.Add(role, user.EnterpriseID, user.UserName);
                if (newid == -1)
                    return Fail("已存在角色");
                if (newid < 1)
                    return Fail("新增失败");
            }
            return OK();
        }
        [HttpPost, UrlAuthorize]
        public ActionResult DeleteRole(string ids)
        {
            var bll = new Core.BLL.Role();
            string errMsg = string.Empty;
            foreach (var id in ids.Split(','))
            {
                errMsg = bll.Delete(Int32.Parse(id));
                if (errMsg.Length > 0)
                    return Fail(errMsg);
            }
            Core.LogHelper.Info("删除角色：" + ids, Entity.Enums.LogType.ManageUser);
            return OK();
        }
        [HttpGet]
        public ActionResult PermissionConfig(string id)
        {
            Core.UrlAuthorizeEntities db = new Core.UrlAuthorizeEntities();
            var bll = new Core.BLL.Role();
            var permissions = bll.Get(Convert.ToInt32(id)).PermissionID.Split(',');
            List<Entity.PermissionQuery> list = new List<Entity.PermissionQuery>();
            foreach (var item in db.PermissionItems)
            {
                list.Add(new Entity.PermissionQuery()
                {
                    ID = item.ID,
                    Name = item.Name,
                    Type = item.Type == 1 ? "显示页面" : item.Type == 2 ? "新增修改保存" : item.Type == 3 ? "删除操作" : item.Type == 4 ? "修改操作" : item.Type == 5 ? "查询操作" : "导出操作",
                    Route = item.Route,
                    isEnable = Array.IndexOf<string>(permissions, item.ID.ToString()) == -1 ? false : true,
                });
            }
            ViewBag.PermissionItems = list;
            ViewBag.RoleID = id;
            return View();
        }
        [HttpPost, UrlAuthorize]
        public ActionResult SavePermissionConfig()
        {
            Dictionary<int, bool> d = new Dictionary<int, bool>();
            Core.UrlAuthorizeEntities db = new Core.UrlAuthorizeEntities();
            foreach (var item in db.PermissionItems)
            {
                d.Add(item.ID,
               Convert.ToBoolean(Request.Form["chb_" + item.ID]));
            }
            int RoleID = Convert.ToInt32(Request.Form["RoleID"]);
            var bll = new Core.BLL.Role();
            var user = base.LoginUser;
            string errMsg = bll.UpdatePermission(d, RoleID, user.UserName);
            if (errMsg.Length > 0)
                return Fail(errMsg);
            return OK();

        }
        #endregion

        #region 用户管理
        [UrlAuthorize]
        public ActionResult UserInfo()
        {
            Core.UrlAuthorizeEntities db = new Core.UrlAuthorizeEntities();
            ViewBag.PermissionList = db.PermissionList;
            return View();
        }
        [HttpPost, UrlAuthorize]
        public ActionResult UserInfoQuery()
        {
            string UserCode = Request.Form["UserCode"];
            string UserName = Request.Form["UserName"];
            var filter = base.GetPageInfo();
            bool asc = filter.asc;
            if (string.IsNullOrWhiteSpace(filter.sort)) filter.sort = "update_time";
            Core.BLL.User_info bll = new Core.BLL.User_info();
            int EnterpriseID = base.GetEnterpriseID();
            if (EnterpriseID == 10001)
                return base.Fail("登陆异常请重新登陆");
            var data = bll.GetRoleQuery(EnterpriseID, UserName, UserCode, filter);
            return base.ToGridJson(data);
        }
        [HttpPost, UrlAuthorize]
        public ActionResult SaveUserInfo(Entity.User_infoQuery qu)
        {
            var bll = new Core.BLL.User_info();
            var user = base.LoginUser;
            if (qu.UserId > 0)
            {
                string errMsg = bll.Update(qu, user.UserName);
                if (errMsg.Length > 0)
                    return Fail(errMsg);
            }
            else
            {
                int newid = bll.Add(qu, user.EnterpriseID, user.EnterpriseCode, user.UserName);
                if (newid == -1)
                    return Fail("已存在用户");
                if (newid < 1)
                    return Fail("新增失败");
            }
            return OK();
        }
        [HttpPost, UrlAuthorize]
        public ActionResult DeleteUserInfo(string ids)
        {
            var bll = new Core.BLL.User_info();
            string errMsg = string.Empty;
            foreach (var id in ids.Split(','))
            {
                errMsg = bll.Delete(Int32.Parse(id));
                if (errMsg.Length > 0)
                    return Fail(errMsg);
            }
            Core.LogHelper.Info("删除用户：" + ids, Entity.Enums.LogType.ManageUser);
            return OK();
        }
        #endregion

        #region 支付记录
        [HttpGet, UrlAuthorize]
        public ActionResult Orders()
        {
            var bll = new Core.BLL.Enterprise();
            int EnterpriseID = base.GetEnterpriseID();//是超级管理员就是获取所有数据//是超级管理员就是获取所有数据
            var list = bll.EnterpriseQuery(EnterpriseID); ;
            if (EnterpriseID == 0)
                list.Add(new Entity.Enterprise() { ID = 0, Enterprise_Code = "0", Enterprise_Name = "全部" });
            var EnterpriseList = list.OrderBy(t => t.ID).ToList();
            ViewBag.EnterpriseList = EnterpriseList;
            return View();
        }
        [HttpPost, UrlAuthorize]
        public ActionResult OrderQuery()
        {
            try
            {
                Entity.OrderQuery summaryData = null;
                var data = this.QueryOrderList(true, out summaryData);
                return base.ToGridJson(data, new
                {
                    order_id = string.Format("合计： 共 {0} 笔订单", data.Total),
                    pay_fee = summaryData.pay_fee,
                    real_fee = summaryData.real_fee,
                    total_fee = summaryData.total_fee
                });
            }
            catch (Exception ex)
            {
                WeChatParking.Core.LogHelper.Error(ex, "查询支付记录");
                Entity.PageList<Entity.OrderQuery> data = new Entity.PageList<Entity.OrderQuery>();
                return base.ToGridJson(data, new
                {
                    order_id = string.Format("合计： 共 {0} 笔订单", 0),
                    pay_fee = 0,
                    real_fee = 0,
                    total_fee = 0
                });
            }
        }
        private Entity.PageList<Entity.OrderQuery> QueryOrderList(bool paged, out Entity.OrderQuery summaryData)
        {
            string where = "where 1=1";
            if (!string.IsNullOrWhiteSpace(Request.Form["order_id"]))
            {
                string order_id = Request.Form["order_id"];
                where += String.Format(" and  o.order_id='{0}' ", order_id);
            }
            if (!string.IsNullOrWhiteSpace(Request.Form["Wxuser_name"]))
            {
                string Wxuser_name = Request.Form["Wxuser_name"];
                where += String.Format("  and o.Wxuser_name LIKE '{%0%}' ", Wxuser_name);
            }
            short payStatus = Util.Conv.ToShort(Request.Form["pay_status"]);

            if (!string.IsNullOrWhiteSpace(Request.Form["paytime_begin"]))
            {
                DateTime begin = Util.Conv.ToDate(Request.Form["paytime_begin"]);
                if (payStatus == 3)
                {
                    where += String.Format("  and o.pay_time >= '{0}' ", begin);
                }
                else
                {
                    where += String.Format("  and o.create_time >= '{0}' ", begin);
                }
            }
            else
            {
                DateTime begin = Util.Conv.ToDate(DateTime.Today.AddDays(-6).ToString());
                where += String.Format("  and o.create_time >= '{0}' ", begin);
            }

            if (!string.IsNullOrWhiteSpace(Request.Form["paytime_end"]))
            {
                DateTime end = Util.Conv.ToDate(Request.Form["paytime_end"]).AddDays(1);
                if (payStatus == 3)
                {
                    where += String.Format("  and o.pay_time <= '{0}' ", end);
                }
                else
                {
                    where += String.Format("  and o.create_time <= '{0}' ", end);
                }
            }
            else
            {
                DateTime end = Util.Conv.ToDate(DateTime.Today.ToString()).AddDays(1);
                where += String.Format("  and o.create_time <= '{0}' ", end);
            }

            if (payStatus > 0) where += String.Format("  and o.pay_status = '{0}' ", payStatus);

            if (!string.IsNullOrWhiteSpace(Request.Form["CCEnterpriseID"]))
            {
                short CCEnterpriseID = Util.Conv.ToShort(Request.Form["CCEnterpriseID"]);
                if (CCEnterpriseID > 0)
                {
                    where += String.Format("  and o.CCEnterpriseID = {0} ", CCEnterpriseID);
                }
            }

            int EnterpriseID = base.GetEnterpriseID();
            if (EnterpriseID > 0) where += String.Format("  and o.EnterpriseID = '{0}' ", EnterpriseID);

            Core.BLL.Order_info bll = new Core.BLL.Order_info();

            var filter = base.GetPageInfo();
            bool asc = filter.asc;
            if (string.IsNullOrWhiteSpace(filter.sort)) filter.sort = "pool_time";

            return bll.QueryOrderList(paged, where, filter, out summaryData);

        }
        [UrlAuthorize]
        public ActionResult DownloadOrders()
        {
            Entity.OrderQuery summaryData = null;
            var data = this.QueryOrderList(false, out summaryData);
            if (data.Total == 0)
                return Fail("无订单数据");

            if (data.Total >= 65535)
                return Fail("数据量太多（超出65535），请缩小查询范围");
            #region 生成文件
            string filePath = Server.MapPath("~/Download");
            if (!System.IO.Directory.Exists(filePath))
                System.IO.Directory.CreateDirectory(filePath);
            string fileName = string.Format("支付明细_{0:yyyyMMddHHmm}.csv", DateTime.Now);
            string tempFileName = System.Guid.NewGuid().ToString() + ".csv";
            var fileStream = System.IO.File.Create(System.IO.Path.Combine(filePath, tempFileName));
            string rowFmt = "{0},{1},{2},{3},{4},{5},{6},{7},{8}";
            System.IO.StreamWriter streamWriter = new System.IO.StreamWriter(fileStream, System.Text.Encoding.UTF8);
            streamWriter.WriteLine(rowFmt, "订单号", "姓名", "车牌号", "支付金额", "支付状态", "物业", "车场", "支付时间", "创建时间");
            foreach (var d in data.DataList)
                streamWriter.WriteLine(rowFmt, d.order_id, d.Wxuser_name, d.car_no, d.total_fee,
                    this.RenderPayStatus(d.pay_status), d.Enterprise_Name, d.CCEnterprise_Name, this.RendertDate(d.pay_time), this.RendertDate(d.create_time));
            streamWriter.Flush();
            streamWriter.Close();
            fileStream.Close();
            #endregion
            return OK(string.Format("/Report/Download?file={0}&filename={1}", Server.UrlEncode(tempFileName), Server.UrlEncode(fileName)));
        }
        private string RenderPayStatus(short payStatus)
        {
            switch (payStatus)
            {
                case 1:
                    return "未支付";
                case 2:
                case 3:
                    return "已支付";
                case 4:
                    return "已退款";
                default:
                    break;
            }
            return string.Empty;
        }
        private string RendertDate(DateTime? date)
        {
            return date.HasValue ? date.Value.ToString("yyyy-MM-dd HH:mm:ss") : string.Empty;
        }
        [HttpPost, UrlAuthorize]
        public ActionResult RetryOrders()
        {
            var loginBll = new Core.BLL.LoginUser();
            var user = base.LoginUser;
            var userDl = loginBll.ValidUser(user.EnterpriseCode, user.UserName, Request.Form["UserPwd"]);
            if (userDl == null)
            {
                return base.Fail("密码错误");
            }
            else
            {
                if (!string.IsNullOrWhiteSpace(Request.Form["order_id"]))
                {
                    var ord = new WeChatParking.Core.BLL.PrepaidOrder().GetOrder(Request.Form["order_id"]);
                    if (ord != null)
                    {
                        string fee = ord.pay_fee.ToString();
                        string chepai = ord.car_no;
                        string upOrdID = ord.order_id;
                        string ordID = ord.order_id;
                        string request = "";
                        int Fee = int.Parse(fee);
                        try
                        {
                            string res = new WeChatParking.Core.Payment.UnionPay.ActiveAct().refundBill(chepai, Fee, upOrdID, ordID, out request);
                           // WeChatParking.Core.LogHelper.Info(request, "无感主动退款订单");
                            //WeChatParking.Core.LogHelper.Info(res, "无感主动退款订单返回");
                            WeChatParking.Core.Payment.UnionPay.RefundInfo rsp = (WeChatParking.Core.Payment.UnionPay.RefundInfo)Newtonsoft.Json.JsonConvert.DeserializeObject(res, typeof(WeChatParking.Core.Payment.UnionPay.RefundInfo));
                        }
                        catch (Exception)
                        {
                            WeChatParking.Core.Payment.UnionPay.retry retryModel = new WeChatParking.Core.Payment.UnionPay.retry()
                            {
                                order_id = ordID,
                                upRefundId = ordID,
                                status = 0,
                                type = 1,
                                time = DateTime.Now,
                                num = 0
                            };
                            new WeChatParking.Core.BLL.retry().Add(retryModel);
                            return Fail("请求退款超时，系统将自动重新请求退款三次");
                        }
                        WeChatParking.Core.Payment.UnionPay.retry retryModel2 = new WeChatParking.Core.Payment.UnionPay.retry()
                        {
                            order_id = ordID,
                            upRefundId = ordID,
                            status = 0,
                            type = 3,
                            time = DateTime.Now,
                            num = 0
                        };
                        new WeChatParking.Core.BLL.retry().Add(retryModel2);
                        return OK();
                    }
                }
                return base.Fail("未找到改订单");
            }
        }
        #endregion

        #region 物业管理
        [UrlAuthorize]
        public ActionResult Enterprise()
        {
            var bll = new Core.BLL.Enterprise();
            int EnterpriseID = base.GetEnterpriseID();//是超级管理员就是获取所有数据//是超级管理员就是获取所有数据
            var list = bll.EnterpriseQuery(EnterpriseID); ;
            if (EnterpriseID == 0)
                list.Add(new Entity.Enterprise() { ID = 0, Enterprise_Code = "0", Enterprise_Name = "无" });
            var EnterpriseList = list.OrderBy(t => t.ID).ToList();
            ViewBag.EnterpriseList = EnterpriseList;
            return View();
        }
        [HttpPost, UrlAuthorize]
        public ActionResult EnterpriseQuery()
        {
            var filter = base.GetPageInfo();
            bool asc = filter.asc;
            if (string.IsNullOrWhiteSpace(filter.sort)) filter.sort = "create_time";
            var bll = new Core.BLL.Enterprise();
            int EnterpriseID = base.GetEnterpriseID();//是超级管理员就是获取所有数据
            var list = bll.EnterpriseQuery(EnterpriseID);
            if (!string.IsNullOrWhiteSpace(Request.Form["enterprise_Name"]))
                list = (from c in list
                        where c.Enterprise_Name.Contains(Request.Form["enterprise_Name"])
                        select c).ToList();

            if (!string.IsNullOrWhiteSpace(Request.Form["enterprise_Code"]))
                list = (from c in list
                        where c.Enterprise_Code.Contains(Request.Form["enterprise_Code"])
                        select c).ToList();
            list = (from c in list
                    where c.Enterprise_FCode.Contains("0")
                    select c).ToList();
            int Total = list.Count;
            int TotalPage = Total / filter.rows + 1;
            list = list.Skip((filter.page - 1) == 0 ? 0 : (filter.page - 1) * filter.rows).Take(filter.rows).ToList();
            WeChatParking.Entity.PageList<Entity.Enterprise> data = new Entity.PageList<Entity.Enterprise>();
            data.DataList = list;
            data.Total = Total;
            data.TotalPage = TotalPage;
            data.Page = filter.page;
            return base.ToGridJson(data);
        }
        [HttpPost, UrlAuthorize]
        public ActionResult SaveEnterprise(Entity.Enterprise val)
        {
            var bll = new Core.BLL.Enterprise();
            var user = base.LoginUser;
            if (val.ID > 0)
            {
                string errMsg = bll.Update(val, user.UserName);

                if (errMsg.Length > 0)
                    return Fail(errMsg);
            }
            else
            {
                int newid = bll.Add(val, user.UserName);
                if (newid == -1)
                {
                    return Fail("已存在物业");
                }
                if (newid < 1)
                {
                    return Fail("新增失败");
                }
            }
            return OK();
        }
        [HttpPost, UrlAuthorize]
        public ActionResult DeleteEnterprise(string ids)
        {
            var bll = new Core.BLL.Enterprise();
            string errMsg = string.Empty;
            foreach (var id in ids.Split(','))
            {
                errMsg = bll.Delete(Int32.Parse(id));
                if (errMsg.Length > 0)
                    return Fail(errMsg);
            }
            Core.LogHelper.Info("删除车场：" + ids, Entity.Enums.LogType.ManageEnterprise);
            return OK();
        }
        #endregion

        #region 停车场管理
        [UrlAuthorize]
        public ActionResult Parking()
        {
            var bll = new Core.BLL.Enterprise();
            int EnterpriseID = base.GetEnterpriseID();//是超级管理员就是获取所有数据//是超级管理员就是获取所有数据
            var list = bll.EnterpriseQuery(EnterpriseID); ;
            if (EnterpriseID == 0)
                list.Add(new Entity.Enterprise() { ID = 0, Enterprise_Code = "0", Enterprise_Name = "无" });
            var EnterpriseList = list.OrderBy(t => t.ID).ToList();
            ViewBag.EnterpriseList = EnterpriseList;
            return View();
        }
        [HttpPost, UrlAuthorize]
        public ActionResult ParkingQuery()
        {
            var filter = base.GetPageInfo();
            bool asc = filter.asc;
            if (string.IsNullOrWhiteSpace(filter.sort)) filter.sort = "create_time";
            var bll = new Core.BLL.Enterprise();
            int EnterpriseID = base.GetEnterpriseID();//是超级管理员就是获取所有数据
            var list = bll.EnterpriseQuery(EnterpriseID);
            if (!string.IsNullOrWhiteSpace(Request.Form["enterprise_Name"]))
                list = (from c in list
                        where c.Enterprise_Name.Contains(Request.Form["enterprise_Name"])
                        select c).ToList();

            if (!string.IsNullOrWhiteSpace(Request.Form["enterprise_Code"]))
                list = (from c in list
                        where c.Enterprise_Code.Contains(Request.Form["enterprise_Code"])
                        select c).ToList();
            list = (from c in list
                    where c.Enterprise_FCode != "0"
                    select c).ToList();
            int Total = list.Count;
            int TotalPage = Total / filter.rows + 1;
            list = list.Skip((filter.page - 1) == 0 ? 0 : (filter.page - 1) * filter.rows).Take(filter.rows).ToList();
            WeChatParking.Entity.PageList<Entity.Enterprise> data = new Entity.PageList<Entity.Enterprise>();
            data.DataList = list;
            data.Total = Total;
            data.TotalPage = TotalPage;
            data.Page = filter.page;
            return base.ToGridJson(data);
        }
        [HttpPost, UrlAuthorize]
        public ActionResult SaveParking(Entity.Enterprise val)
        {
            var bll = new Core.BLL.Enterprise();
            var user = base.LoginUser;
            if (val.ID > 0)
            {
                string errMsg = bll.Update(val, user.UserName);

                if (errMsg.Length > 0)
                    return Fail(errMsg);
            }
            else
            {
                int newid = bll.Add(val, user.UserName);
                if (newid == -1)
                {
                    return Fail("已存在物业");
                }
                if (newid < 1)
                {
                    return Fail("新增失败");
                }
            }
            return OK();
        }
        [HttpPost, UrlAuthorize]
        public ActionResult DeleteParking(string ids)
        {
            var bll = new Core.BLL.Enterprise();
            string errMsg = string.Empty;
            foreach (var id in ids.Split(','))
            {
                errMsg = bll.Delete(Int32.Parse(id));
                if (errMsg.Length > 0)
                    return Fail(errMsg);
            }
            Core.LogHelper.Info("删除车场：" + ids, Entity.Enums.LogType.ManageEnterprise);
            return OK();
        }
        [UrlAuthorize]
        public ActionResult ParkingConfig(string id)
        {
            var model = new Core.BLL.ParkingInfo().Get(Convert.ToInt32(id));
            ViewBag.par = model;
            ViewBag.pID = id;
            return View();
        }
        [HttpPost, UrlAuthorize]
        public ActionResult SaveParkingConfig(Entity.ParkingInfo val)
        {

            val.updateTime = DateTime.Now;
            if (val.ID > 0)
            {
                new Core.BLL.ParkingInfo().Update(val);
            }
            else
            {
                string name = new Core.BLL.Enterprise().Get(val.parkId).Enterprise_Name;
                val.parkName = name;
                new Core.BLL.ParkingInfo().Add(val);
            }
            return OK();
        }
        #endregion

        #region 出入记录
        [UrlAuthorize]
        public ActionResult CarRecord()
        {
            var bll = new Core.BLL.Enterprise();
            int EnterpriseID = base.GetEnterpriseID();//是超级管理员就是获取所有数据//是超级管理员就是获取所有数据
            var list = bll.EnterpriseQuery(EnterpriseID); ;
            list.Add(new Entity.Enterprise() { ID = 0, Enterprise_Code = "0", Enterprise_Name = "全部" });
            var EnterpriseList = list.OrderBy(t => t.ID).ToList();
            ViewBag.EnterpriseList = EnterpriseList;
            return View();
        }
        [UrlAuthorize]
        public ActionResult CarRecordQuery()
        {
            Entity.CarRecord summaryData = null;
            var data = this.QueryCarRecordList(true, out summaryData);
            return base.ToGridJson(data, new
            {
                order_id = string.Format("合计： 共 {0} 笔记录", data.Total),
                Y_fee = summaryData.Y_fee,
                S_fee = summaryData.S_fee,
                YH_fee = summaryData.YH_fee
            });
        }
        private Entity.PageList<Entity.CarRecord> QueryCarRecordList(bool paged, out Entity.CarRecord summaryData)
        {
            var filter = base.GetPageInfo();
            if (string.IsNullOrWhiteSpace(filter.sort))
            {
                filter.sort = "create_time";
                filter.asc = false;
            }
            if (paged == false)
            {
                filter.page = 1;
                filter.rows = Int32.MaxValue;
            }
            bool asc = filter.asc;
            if (string.IsNullOrWhiteSpace(filter.sort)) { filter.sort = "create_time"; filter.asc = false; }
            IList<ISort> sort = new List<ISort>
            {
                new Sort{ PropertyName = filter.sort, Ascending = filter.asc}
            };
            System.Text.StringBuilder sumSql = new System.Text.StringBuilder()
                .Append("SELECT SUM(Y_fee) Y_fee")
                .Append(",SUM(S_fee) S_fee")
                .Append(",SUM(YH_fee) YH_fee")
                .Append(" from CarRecord where 1=1 ");
            dynamic sqlParam = new System.Dynamic.ExpandoObject();
            var pgMain = new PredicateGroup { Operator = GroupOperator.And, Predicates = new List<IPredicate>() };
            short status = Util.Conv.ToShort(Request.Form["status"]);
            if (0 < status && status < 100)
            {
                pgMain.Predicates.Add(Predicates.Field<Entity.CarRecord>(t => t.status, Operator.Eq, status));
                sumSql.Append(" and status=@status");
                sqlParam.status = status;
            }
            if (!string.IsNullOrWhiteSpace(Request.Form["time_begin"]))
            {
                DateTime begin = Util.Conv.ToDate(Request.Form["time_begin"]);
                pgMain.Predicates.Add(Predicates.Field<Entity.CarRecord>(t => t.inTime, Operator.Ge, begin));
                sumSql.Append(" and inTime>=@inTime");
                sqlParam.inTime = begin;
            }
            else
            {
                DateTime begin = Util.Conv.ToDate(DateTime.Today.AddDays(-6).ToString());
                pgMain.Predicates.Add(Predicates.Field<Entity.CarRecord>(t => t.inTime, Operator.Ge, begin));
                sumSql.Append(" and inTime>=@inTime");
                sqlParam.inTime = begin;
            }
            if (!string.IsNullOrWhiteSpace(Request.Form["time_end"]))
            {
                DateTime end = Util.Conv.ToDate(Request.Form["time_end"]).AddDays(1);
                pgMain.Predicates.Add(Predicates.Field<Entity.CarRecord>(t => t.inTime, Operator.Lt, end));
                sumSql.Append(" and inTime<@inTime");
                sqlParam.inTime = end;
            }
            else
            {
                DateTime end = Util.Conv.ToDate(DateTime.Today.ToString());
                pgMain.Predicates.Add(Predicates.Field<Entity.CarRecord>(t => t.inTime, Operator.Lt, end));
                sumSql.Append(" and inTime<@inTime");
                sqlParam.inTime = end;
            }
            int EnterpriseID = base.GetEnterpriseID();//是超级管理员就是获取所有数据//是超级管理员就是获取所有数据
            if (EnterpriseID > 0)
            {
                pgMain.Predicates.Add(Predicates.Field<Entity.CarRecord>(t => t.Enterprise_ID, Operator.Eq, EnterpriseID));
                sumSql.Append(" and Enterprise_ID=@Enterprise_ID");
                sqlParam.Enterprise_ID = EnterpriseID;
            }
            // Enterprise_Code
            string Enterprise_Code = Request.Form["Enterprise_Code"];
            if (!string.IsNullOrWhiteSpace(Enterprise_Code))
            {
                if (Enterprise_Code != "0")
                {
                    pgMain.Predicates.Add(Predicates.Field<Entity.CarRecord>(t => t.Enterprise_Code, Operator.Eq, Enterprise_Code));
                    sumSql.Append(" and Enterprise_Code=@Enterprise_Code");
                    sqlParam.Enterprise_Code = Enterprise_Code;
                }
            }
            using (var dbContext = Repository.DbContext.Create())
            {
                var data = dbContext.GetPageList<Entity.CarRecord>(pgMain, sort, filter);
                summaryData = dbContext.GetListBySql<Entity.CarRecord>(sumSql.ToString(), (object)sqlParam).FirstOrDefault();
                return data;
            }
        }
        [UrlAuthorize]
        public ActionResult DownloadCarRecor()
        {
            Entity.CarRecord summaryData = null;
            var data = this.QueryCarRecordList(false, out summaryData);
            if (data.Total == 0)
                return Fail("无订单数据");
            if (data.Total >= 65535)
                return Fail("数据量太多（超出65535），请缩小查询范围");
            #region 生成文件
            string filePath = Server.MapPath("~/Download");
            if (!System.IO.Directory.Exists(filePath))
                System.IO.Directory.CreateDirectory(filePath);
            string fileName = string.Format("出入记录_{0:yyyyMMddHHmm}.csv", DateTime.Now);
            string tempFileName = System.Guid.NewGuid().ToString() + ".csv";
            var fileStream = System.IO.File.Create(System.IO.Path.Combine(filePath, tempFileName));
            string rowFmt = "{0},{1},{2},{3},{4},{5},{6},{7},{8},{9}";
            System.IO.StreamWriter streamWriter = new System.IO.StreamWriter(fileStream, System.Text.Encoding.UTF8);
            streamWriter.WriteLine(rowFmt, "车牌号", "车型", "车场代码", "车场名", "应缴", "优惠", "实缴", "状态", "进场时间", "出场时间", "创建时间");
            foreach (var d in data.DataList)
                streamWriter.WriteLine(rowFmt, d.carBrand, this.carRetain1(d.retain1), d.Enterprise_Code, d.Enterprise_Name, d.Y_fee, d.YH_fee, d.S_fee,
                    this.carStatus(d.status), this.RendertDate(d.inTime), this.RendertDate(d.outTime), this.RendertDate(d.create_time));
            streamWriter.Flush();
            streamWriter.Close();
            fileStream.Close();
            #endregion
            return OK(string.Format("/Report/Download?file={0}&filename={1}", Server.UrlEncode(tempFileName), Server.UrlEncode(fileName)));
        }
        private string carStatus(int Status)
        {
            switch (Status)
            {
                case 1:
                    return "在场";
                case 2:
                    return "出场";
                default:
                    break;
            }
            return string.Empty;
        }
        private string carRetain1(string retain1)
        {
            switch (retain1)
            {
                case "1":
                    return "小车";
                case "":
                    return "货车";
                default:
                    break;
            }
            return string.Empty;
        }
        #endregion

        #region 出入口管理
        [UrlAuthorize]
        public ActionResult Device()
        {
            var bll = new Core.BLL.Enterprise();
            int EnterpriseID = base.GetEnterpriseID();//是超级管理员就是获取所有数据//是超级管理员就是获取所有数据
            var list = bll.EnterpriseQuery(EnterpriseID); ;
            ViewBag.EnterpriseList = list;
            return View();
        }
        [HttpPost, UrlAuthorize]
        public ActionResult DeviceQuery()
        {
            var filter = base.GetPageInfo();
            bool asc = filter.asc;
            if (string.IsNullOrWhiteSpace(filter.sort)) filter.sort = "create_time";
            IList<ISort> sort = new List<ISort>
            {
                new Sort{ PropertyName = filter.sort, Ascending = filter.asc}
            };
            var pgMain = new PredicateGroup { Operator = GroupOperator.And, Predicates = new List<IPredicate>() };
            if (!string.IsNullOrWhiteSpace(Request.Form["device_Code"]))
                pgMain.Predicates.Add(Predicates.Field<Entity.Device>(t => t.DeviceClient_code, Operator.Eq, Request.Form["device_Code"]));
            if (!string.IsNullOrWhiteSpace(Request.Form["device_Name"]))
                pgMain.Predicates.Add(Predicates.Field<Entity.Device>(t => t.Device_name, Operator.Like, "%" + Request.Form["device_Name"] + "%"));
            int EnterpriseID = base.GetEnterpriseID();
            if (EnterpriseID == 10001)
                return base.Fail("登陆异常请重新登陆");
            if (EnterpriseID != 0)
                pgMain.Predicates.Add(Predicates.Field<Entity.Device>(t => t.Enterprise_ID, Operator.Eq, EnterpriseID));
            using (var db = Repository.DbContext.Create())
            {
                var data = db.GetPageList<Entity.Device>(pgMain, sort, filter);
                return base.ToGridJson(data);
            }
        }
        [HttpPost, UrlAuthorize]
        public ActionResult SaveDevice(Entity.Device de)
        {
            var bll = new Core.BLL.Device();
            var user = base.LoginUser;
            if (de.ID > 0)
            {
                string errMsg = bll.Update(de, user.UserName);
                if (errMsg.Length > 0)
                    return Fail(errMsg);
            }
            else
            {
                int newid = bll.Add(de, user.UserName);
                if (newid == -1)
                    return Fail("已存在用户");
                if (newid < 1)
                    return Fail("新增失败");
            }
            return OK();
        }
        [HttpPost, UrlAuthorize]
        public ActionResult DeleteDevice(string ids)
        {
            var bll = new Core.BLL.Device();
            string errMsg = string.Empty;
            foreach (var id in ids.Split(','))
            {
                errMsg = bll.Delete(Int32.Parse(id));
                if (errMsg.Length > 0)
                    return Fail(errMsg);
            }
            Core.LogHelper.Info("删除出入口：" + ids, Entity.Enums.LogType.ManageUser);
            return OK();
        }
        public ActionResult PayQRcode()
        {
            return View();
        }
        #endregion
        /// <summary>
        /// 页面未授权
        /// </summary>
        /// <returns></returns>
        public ActionResult Unauthenticated()
        {
            return View();
        }

        public ActionResult test()
        {
            return View();
        }
        public ActionResult testPost(int type, string chepai, string fee, string ordID, string upOrdID)
        {
            //查询车辆状态
            if (type == 1)
            {
                string request = "";
                var res = new WeChatParking.Core.Payment.UnionPay.ActiveAct().carStatusQuery(chepai, out  request);
                WeChatParking.Core.LogHelper.Info(request, WeChatParking.Entity.Enums.LogType.UnionPay_carStatus);
                WeChatParking.Core.LogHelper.Info(res, "无感主动查询车辆状态请返回");
            }
            //进场
            else if (type == 2)
            {
                WeChatParking.Core.BLL.ServerCode bll = new WeChatParking.Core.BLL.ServerCode();
                bll.ServerAddIn(new WeChatParking.Entity.Api.InOrOut()
                {
                    Car_plate = chepai,
                    Time = "201809061545",
                    Type = 0,
                    Car_type = 1,
                    ImgLen = 100,
                    CarUser_type = 1,
                    Parking_code = "24566876fgdffs23",
                    Guid = DateTime.Now.ToString()
                }, "1243.jpg");
            }
            //出场
            else if (type == 3)
            {
                string request = "";
                var res = new WeChatParking.Core.Payment.UnionPay.ActiveAct().noticeExit("100", chepai, DateTime.Now.AddMinutes(-15), "3", "一指通停车场001", out request);
                WeChatParking.Core.BLL.ServerCode bll = new WeChatParking.Core.BLL.ServerCode();
                bll.ServerAddOut(new WeChatParking.Entity.Api.InOrOut()
                {
                    Car_plate = chepai,
                    Time = "201809061553",
                    Type = 1,
                    Car_type = 1,
                    ImgLen = 100,
                    CarUser_type = 1,
                    Parking_code = "24566876fgdffs23",
                    Guid = DateTime.Now.ToString()
                }, "1243.jpg");
            }
            //无感缴费
            else if (type == 4)
            {
                int Fee = int.Parse(fee);
                WeChatParking.Core.BLL.ServerCode bll = new WeChatParking.Core.BLL.ServerCode();
                bll.XCPay(new WeChatParking.Entity.Api.XCPay()
                {
                    Parking_code = "24566876fgdffs23",
                    Car_plate = chepai,
                    Fee = Fee,
                    Time = "201809061545",

                });
            }
            //订单查询
            else if (type == 5)
            {
                string request = "";
                string res = new WeChatParking.Core.Payment.UnionPay.ActiveAct().payStatus(ordID, out request);
                WeChatParking.Core.LogHelper.Info(request, "无感主动支付订单查询");
                WeChatParking.Core.LogHelper.Info(res, "无感主动支付订单查询返回");
            }
            //退款
            else if (type == 6)
            {
                string request = "";
                int Fee = int.Parse(fee);
                try
                {
                    string res = new WeChatParking.Core.Payment.UnionPay.ActiveAct().refundBill(chepai, Fee, upOrdID, ordID, out request);
                    WeChatParking.Core.LogHelper.Info(request, "无感主动退款订单");
                    WeChatParking.Core.LogHelper.Info(res, "无感主动退款订单返回");
                    WeChatParking.Core.Payment.UnionPay.RefundInfo rsp = (WeChatParking.Core.Payment.UnionPay.RefundInfo)Newtonsoft.Json.JsonConvert.DeserializeObject(res, typeof(WeChatParking.Core.Payment.UnionPay.RefundInfo));
                }
                catch (Exception)
                {
                    WeChatParking.Core.Payment.UnionPay.retry retryModel = new WeChatParking.Core.Payment.UnionPay.retry()
                    {
                        order_id = ordID,
                        upRefundId = ordID,
                        status = 0,
                        type = 1,
                        time = DateTime.Now,
                        num = 0
                    };
                    new WeChatParking.Core.BLL.retry().Add(retryModel);
                    return Fail("退款超时");
                }
                WeChatParking.Core.Payment.UnionPay.retry retryModel2 = new WeChatParking.Core.Payment.UnionPay.retry()
                {
                    order_id = ordID,
                    upRefundId = ordID,
                    status = 0,
                    type = 3,
                    time = DateTime.Now,
                    num = 0
                };
                new WeChatParking.Core.BLL.retry().Add(retryModel2);


            }
            //退款查询
            else if (type == 7)
            {
                string request = "";
                string res = new WeChatParking.Core.Payment.UnionPay.ActiveAct().refundStatus(ordID, upOrdID, out request);
                WeChatParking.Core.LogHelper.Info(request, "无感主动退款订单查询");
                WeChatParking.Core.LogHelper.Info(res, "无感主动退款订单查询返回");

            }
            //预缴费用完成
            else if (type == 8)
            {
                //下发缴费记录
                Entity.Api.YPay ypay = new Entity.Api.YPay()
                {
                    DeviceClient_code = "24566876fgdffs23",
                    EnterpriseID = 1,
                    State = 1,
                    Car_plate = chepai,
                    Time = DateTime.Now.ToString("yyyyMMddHHmm"),
                    Fee = Convert.ToInt32(fee),
                    CarUser_type = 1,//9开闸
                    order_id = DateTime.Now.ToString("yyyyMMddHHmm"),
                    Guid = Guid.NewGuid().ToString("N"),
                    create_time = DateTime.Now,
                };
                using (var dbContext = Repository.DbContext.Create())
                {
                    dbContext.Insert(ypay);
                }
            }
            else if (type == 9)
            {
                //下发缴费记录
                Entity.Api.YPay ypay = new Entity.Api.YPay()
                {
                    DeviceClient_code = "24566876fgdffs23",
                    EnterpriseID = 1,
                    State = 1,
                    Car_plate = chepai,
                    Time = DateTime.Now.ToString("yyyyMMddHHmm"),
                    Fee = Convert.ToInt32(fee),
                    CarUser_type = 9,//9开闸
                    order_id = DateTime.Now.ToString("yyyyMMddHHmm"),
                    Guid = Guid.NewGuid().ToString("N"),
                    create_time = DateTime.Now,
                };
                using (var dbContext = Repository.DbContext.Create())
                {
                    dbContext.Insert(ypay);
                }
            }
            else if (type == 10)
            {
                Core.BLL.ServerCode serverbll = new Core.BLL.ServerCode();
                var feeModel = new Entity.Api.FeeQuery()
                {
                    Car_plate = chepai,
                    Time = DateTime.Now.ToString("yyyyMMddHHmm"),
                    Guid = Guid.NewGuid().ToString("N"),
                    DeviceClient_code = "24566876fgdffs23",
                    EnterpriseID = 1,
                    CCEnterpriseName = "一指通停车场001"
                };
                //下发计费查询指令
                serverbll.AddFeeQuery(feeModel);
                string code = "";
                bool isOK = TcpServerController.Send(WeChatParking.Core.TCPServer.SendDatas.zhuDongFeeQuery(feeModel, ref code), code);
                if (isOK)
                {
                    serverbll.UpdateFeeQuery(feeModel.Guid, 2);
                }
            }
            return OK();
        }
    }
}
